import { createApp } from 'vue'
import Confirm from './Confirm.vue'

function confirm(title, confirmText, cancelText) {
  return new Promise((resolve, reject) => {
    const app = createApp(Confirm, {
      title,
      confirmText,
      cancelText
    })
    const instance = app.mount(document.createElement('div'))
    document.body.append(instance.$el)
    instance.visible = true

    function unMount() {
      setTimeout(() => {
        app.unmount()
      }, 400)
    }

    instance.$watch(
      () => instance.confirmClicked,
      newValue => {
        if (newValue) {
          unMount()
          resolve()
        }
      }
    )

    instance.$watch(
      () => instance.cancelClicked,
      newValue => {
        if (newValue) {
          unMount()
          // eslint-disable-next-line
          reject()
        }
      }
    )
  })
}

export default confirm
